package com.myecl.poker.rules;


import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;

import com.myecl.poker.rules.enums.Hands;




public class Hand {
	Hands hand = null;
	Card[] cards = new Card[5];
	
	public Hand(List<Card> cards) {
		Hands[] hands = Hands.values();
		for(int i = hands.length - 1; i >= 0 && hand == null; i--) {
			Card[] handCards = hands[i].evaluate(cards);
			if(handCards != null) {
				hand = hands[i];
				this.cards = fillHand(cards, Arrays.asList(handCards));
			}
		}
	}
	
	public Hands getHand() {
		return hand;
	}
	
	public Card[] getCards() {
		return cards;
	}

	
	private Card[] fillHand(List<Card> fillWith, List<Card> toBeFilled) {
		fillWith = new LinkedList<Card>(fillWith);
		TreeSet<Card> resultSet = new TreeSet<Card>(toBeFilled);
		while(resultSet.size() < 5 && resultSet.size() < fillWith.size()) {
			Card[] card = Hands.HIGH_CARD.evaluate(fillWith);
			if (!resultSet.contains(card[0])) {
				resultSet.add(card[0]);	
			} 
			fillWith.remove(card[0]);
		}
		Card[] result = new Card[resultSet.size()];
		for (int i = 0; i < result.length; i++) {
			result[i] = resultSet.pollFirst();		
		}
		return resultSet.toArray(new Card[5]);
	}
	
}











